package com.hexacta.radio.persistence;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import com.hexacta.radio.model.Dial;
import com.hexacta.radio.model.Radio;

public class RadioRepository extends HibernateRepository {

	private static final String FIRST_DIAL = "89.0";
	private static final String LAST_DIAL = "107.9";
	private static final BigDecimal DIAL_DIF = new BigDecimal("0.1");
	private String cadena;
	
	public RadioRepository() {
		super();
	}
	
	@Transactional
	public Radio getRadio() {
		List<Radio> radios = (List<Radio>) this.select("from Radio");
		if (radios.isEmpty()) {
			Radio radio = new Radio(false, this.getDials());
			this.save(radio);
			return radio;
		}
		return radios.get(0);
	}

	private List<Dial> getDials() {
		List<Dial> dials = (List<Dial>) this.select("from Dial");
		if (dials.isEmpty()) {
			dials = inicializarEmisoras();
			return dials;
		}
		return dials;
	}

	private static List<Dial> inicializarEmisoras() {
		List<Dial> dials = new ArrayList<Dial>();
		BigDecimal newDial = new BigDecimal(FIRST_DIAL);
		BigDecimal lastDial = new BigDecimal(LAST_DIAL);
		while (newDial.compareTo(lastDial) <= 0) {
			dials.add(new Dial(newDial.toString(), ""));
			newDial = newDial.add(DIAL_DIF);
		}
		return dials;
	}

}
